from django.shortcuts import render


from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import hashlib
import xml.etree.ElementTree as ET
from django.conf import settings


from django.contrib.auth.decorators import login_required
from django.contrib.admin.views.decorators import staff_member_required
from .models import InGarageReport, OutGarageReport, MailKey, ItemSentback, VehicleMaintenance, KeyDuplication


# # from .models import Bill
# from .models import VehicleRecord


@login_required
@staff_member_required  # 确保只有已登录的用户才能访问
def my_page_view(request):
    # 获取当前用户
    user = request.user

    # 查询与用户相关的报备记录数量
    in_garage_count = InGarageReport.objects.filter(user=user).count()
    out_garage_count = OutGarageReport.objects.filter(user=user).count()
    mail_key_count = MailKey.objects.filter(user=user).count()
    item_sentback_count = ItemSentback.objects.filter(user=user).count()
    vehicle_maintenance_count = VehicleMaintenance.objects.filter(user=user).count()
    key_duplication_count = KeyDuplication.objects.filter(user=user).count()

    context = {
        'user': user,
        'in_garage_count': in_garage_count,
        'out_garage_count': out_garage_count,
        'mail_key_count': mail_key_count,
        'item_sentback_count': item_sentback_count,
        'vehicle_maintenance_count': vehicle_maintenance_count,
        'key_duplication_count': key_duplication_count,
    }
    return render(request, 'admin/my_page.html', context)




@csrf_exempt
def payment_notification(request):
    if request.method == 'POST':
        # 获取POST请求体
        xml_data = request.body
        # 解析XML
        xml_dict = parse_xml_to_dict(xml_data)

        # 1. 验证请求的真实性（例如, 对于微信支付, 验证签名）
        api_key = settings.API_KEY
        if not verify_signature(xml_dict, api_key):
            return HttpResponse('Signature verification failed', status=403)

        # 2. 解析支付结果
        payment_result = xml_dict['result_code']

        # 3. 根据支付结果更新订单状态
        if payment_result == 'SUCCESS':
            order_id = xml_dict['out_trade_no']
            update_order_status(order_id, 'paid')

        # 4. 返回响应给支付平台, 例如微信支付要求返回特定的XML格式响应
        return HttpResponse('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>', content_type='text/xml')
    else:
        # 非POST请求, 返回错误
        return HttpResponse('Invalid Request', status=400)
    


def parse_xml_to_dict(xml_data):
    """将XML数据解析为字典"""
    root = ET.fromstring(xml_data)
    return {child.tag: child.text for child in root}

def verify_signature(xml_dict, api_key ):
    """验证签名（这里需要根据实际情况实现签名验证逻辑）"""
    # 假设签名验证逻辑
    # return True

    """
    验证微信支付通知的签名
    :param xml_dict: 解析支付通知XML得到的字典
    :param api_key: 微信商户平台设置的API密钥
    :return: 验证结果,True表示验证通过, False表示验证失败
    """
    # 从参数中移除sign
    if 'sign' not in xml_dict:
        return False
    sign = xml_dict.pop('sign')
    
    # 按照字段名的ASCII码从小到大排序后, 使用URL键值对的格式拼接成字符串
    sorted_params = sorted(xml_dict.items())
    stringA = "&".join(["{}={}".format(k, v) for k, v in sorted_params])
    
    # 在stringA最后拼接上key得到stringSignTemp字符串, 并对stringSignTemp进行MD5运算, 再将得到的字符串所有字符转换为大写
    stringSignTemp = "{}&key={}".format(stringA, api_key)
    signValue = hashlib.md5(stringSignTemp.encode("utf-8")).hexdigest().upper()
    
    # 比较计算得到的签名值与通知中的签名值
    return sign == signValue


def update_order_status(order_id, status):
    """根据支付结果更新订单状态（这里需要根据实际情况实现订单状态更新逻辑）"""
    # 假设更新订单状态的逻辑
    return True
    # ogr = OutGarageReport.objects.get(payment_link=order_id)
    # ogr.payment_status = status
    # ogr.save()
